package com.apt.action;

import com.apt.common.AptException;
import com.apt.facade.DataStoreHelper;
import com.apt.model.LoginDetails;

public class LoginAction extends AptBaseAction {

	private static final long serialVersionUID = 1L;
	private String username;
	private String password;

	public String authenticate() {
		String target = null;
		try {

			//System.out.println("LOGIN: USername received is:" + username);
			LoginDetails login= DataStoreHelper.validateUserAndPwd(username,password);
			Integer roleId = login.getRoleId();
					
			if (roleId == null) {
				addActionError(getText("error.login"));
				return "error";

			} else {
				String roleName = DataStoreHelper.getRoleName(roleId);
				if (roleName == null) {
					addActionError(getText("error.role"));
					return "error";

				}
				session.put("loggedInUser", username);
				session.put("loggedFirstName", login.getFirstName());
				if (roleName.equalsIgnoreCase("admin")) {
					target = "admin";
				} else {
					target = "student";
				}
			}
			//System.out.println("The session in Login is:" + session);
			//System.out.println("The userid in Login is:" + session.get("loggedInUser"));
			return target;
		} catch (AptException apt) {
			addActionError(apt.getMessage());
			return "error";

		}

	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
